<template>
  <div
    v-loading="loading"
    class="app-container"
    :element-loading-text="loadingValue"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(255, 255, 255, 0.8)"
  >
    <div class="filter-container queryTool">
      <el-input v-model="listQuery.name" placeholder="文件名称" style="width: 200px" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.anotherName" placeholder="别名" style="width: 200px" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="文件名称" prop="name" width="150px" align="center" />
      <el-table-column label="文件地址" prop="path" align="center" />
      <el-table-column label="别名" prop="anotherName" width="150px" align="center" />
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button size="mini" type="success" @click="importData(row)">
            导入
          </el-button>
          <el-button type="primary" size="mini" @click="downloadFile(row)">
            下载
          </el-button>
          <el-button size="mini" type="danger" @click="deleteFile(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">

      <el-upload
        ref="upload"
        class="myElUpload"
        drag
        :auto-upload="false"
        :on-success="onSuccess"
        :on-exceed="onExceed"
        :limit="1"
        action="http://localhost:8080/file"
      >
        <!--      TODO 上面链接改为 文件接口  -->
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip">请勿乱传</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="createData()">
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, deleteFile, fetchPv, updateArticle } from '@/api/article'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      startDate: 0,
      totalDataNum: 0,
      importTDNum: 0,
      message: '',
      type: '',
      exportSize: 0,
      loadingValue: 0,
      loading: false,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        anotherName: undefined,
        name: undefined
      },
      importanceOptions: [1, 2, 3],
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false,
      websock: null,
      cache: null,
      interval: null
    }
  },
  created() {
    this.getList()
  },
  destroyed() {
    this.websock.close() // 离开路由之后断开websocket连接
    this.websock = null
  },
  methods: {
    getList() {
      this.listLoading = false
      // 实际找到的 import { fetchList, fetchPv, updateArticle } from '@/api/article'中fetchList方法
      fetchList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 导入
    importData(row) {
      this.totalDataNum = 0
      this.importTDNum = 0
      this.exportSize = row.fileSize
      // 开启遮罩
      this.loading = true
      const common = this
      common.cache = row
      const webUrl = 'ws://localhost:8080/websocket/file/importData'
      common.websock = new WebSocket(webUrl)
      common.websock.onmessage = common.websocketOnMessage
      common.websock.onopen = common.websocketOnOpen
      common.websock.onerror = common.websocketOnError
      common.websock.onclose = common.websocketClose
    },
    websocketOnOpen() { // 连接建立之后执行send方法发送数据
      const common = this
      console.log('连接建立之后执行send方法发送数据')
      common.websock.send(common.cache.id)
    },
    websocketOnError() {
      // 连接建立失败重连
      this.$alert('创建连接失败,请刷新,清理缓存后尝试', '异常通知', {
        confirmButtonText: '确定'
      })
      // 收到结果关闭遮罩
      this.loading = false
    },
    websocketOnMessage(e) {
      const redata = JSON.parse(e.data)
      // 获取总的上传数据
      if (redata.state === '0') {
        this.totalDataNum = parseInt(redata.value)
        this.loadingValue = '导入中...(' + 0 + '%)'
        this.startDate = new Date().getTime()
        return
      }
      // 每一次执行插入读取的数据
      if (redata.state === '1') {
        this.importTDNum += parseInt(redata.value)
        const percentage = (this.importTDNum / this.totalDataNum) * 100
        this.loadingValue = '导入中...(' + this.numFilter(percentage) + '%)'
        // console.log(this.loadingValue)
        return
      }
      // 数据导入完成
      if (redata.state === '3') {
        this.loadingValue = '导入完成(' + 100 + '%)'
        this.loading = false
        // 断开websocket连接
        this.websock.close()
        this.websock = null
        this.$alert(',耗时:' + (new Date().getTime() - this.startDate) + '毫秒', '数据导入通知', {
          confirmButtonText: '确定'
        })
        return
      }
    },
    websocketClose(e) {
      console.log('断开连接')
      // 收到结果关闭遮罩
      this.loading = false
    },
    deleteFile(row, index) {
      deleteFile({ id: row.id }).then(response => {
        this.$notify({
          title: response.title,
          message: response.message,
          type: response.type,
          duration: 2000
        })
        // this.list.splice(index, 1)  // 删除这一行数据
        this.getList()
      })
    },
    downloadFile(row) {
      const aTag = document.createElement('a')
      aTag.href = 'http://localhost:8080/file/downloadFile?id=' + row.id // 文件id
      aTag.click()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },
    // 选择多个文件的回调
    onExceed(files, fileList) {
      this.$alert('请勿选择多个文件,一次只能上传一个', '警告', {
        confirmButtonText: '确定',
        callback: action => {}
      })
    },
    // 上传完成的回调
    onSuccess(response, file, fileList) {
      this.dialogFormVisible = false
      this.getList()
    },
    // 添加-- 改成上传文件
    handleCreate() {
      // 显示上传组件
      this.dialogFormVisible = true
      // 清空上传列表
      this.$refs.upload.clearFiles()
    },
    // 确定按钮
    createData() {
      // 调用控件的 上传方法
      this.$refs.upload.submit()
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateArticle(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    // row中包含的是数据，index是当前表格第几行
    handleDelete(row, index) {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    // 截取当前数据到小数点后两位
    numFilter(value) {
      const realVal = parseFloat(value).toFixed(2)
      return realVal
    }
  }
}
</script>

<style lang="scss" scoped>
  .myElUpload ::v-deep .el-upload .el-upload-dragger {
    width: 880px;
    height: 200px;
  }
</style>
